package apptoko.com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event;
import apptoko.com.event.Event.ConvertLinkFail;
import apptoko.com.event.Event.ConvertLinkSuccess;
import apptoko.com.event.Exception.AppJSONException;
import apptoko.com.event.Exception.NetworkIOE;
import apptoko.com.fragment.BaseFragment;
import apptoko.com.model.FBFeedItem;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.NewsFeedListView;
import apptoko.com.view.PullToRefreshListView;
import apptoko.com.view.ScaleImageView;
import apptoko.com.view.PullToRefreshListView.OnRefreshListener;
import apptoko.com.view.SuperNewsFeedListView.OnLoadMoreListener;

import com.androidquery.AQuery;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

@SuppressLint("SetJavaScriptEnabled")
public class NewsFeedActivity extends BaseFragment implements OnLoadMoreListener, OnItemClickListener, OnRefreshListener {

	private String currentStore = "";
	private List<FBFeedItem> feedList;
	private List<FBFeedItem> feedAllList=new ArrayList<FBFeedItem>();
	private BackgroundTasks bgTask;
	private AQuery aquery;
	private NewsFeedListView listView;
//	private int startup = 1;
	private FeedItemAdapter feedAdapter;
//	private View bannerLayout;
	private int LIMIT = 250;
	private String accessToken;
	private ProgressDialog pDialog;
//	private String countryCode;
//	private boolean isRooted;
//	private ProgressDialog progressLoading;
//	private String updateUri;
	private int START=0;
	private final String KEY_CONTENT = "Fragment:List";
//	private TextView viewMore;
	private ProgressBar progressBar;
	public static final int REQUEST_CODE = 99;
	private Handler handler;
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		if (savedInstanceState != null) {
            topType = savedInstanceState.getString(KEY_CONTENT);
        }
//		EventBus.getDefault().register(this);
//		currentStore = Utils.getStaticCurrentStore(getActivity());
		
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, topType);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mParent = inflater.inflate(R.layout.activity_newsfeed, null);
		listView = (NewsFeedListView) mParent.findViewById(R.id.list_feed);
		feedList = new ArrayList<FBFeedItem>();
		feedAdapter = new FeedItemAdapter(getActivity(), R.layout.feed_item, feedList);
		progressBar = (ProgressBar) mParent.findViewById(R.id.loadingDummy);
		handler=new Handler();
//		viewMore=(TextView)mParent.findViewById(R.id.viewmore);
//		viewMore.setOnClickListener(new OnClickListener() {
			
//			@Override
//			public void onClick(View v) {
//				viewMore();
//				
//			}
//		});
		EasyTracker.getInstance().setContext(getActivity());
//		startup = getActivity().getIntent().getIntExtra(Constants.STATE, 1);
//		bannerLayout = inflater.inflate(R.layout.banner_fragment, null);
//		if(countryCode.equalsIgnoreCase("vn")){
//			listView.addHeaderView(bannerLayout, null, false);
//		}
		listView.setAdapter(feedAdapter);
		listView.setOnItemClickListener(this);
		listView.setOnLoadMoreListener(this);
		listView.setOnRefreshListener(this);
		
//		FragmentManager fm = getActivity().getSupportFragmentManager();
//		ParentBannerSlideFragment frag = (ParentBannerSlideFragment) fm.findFragmentById(R.id.banner_fragment);
//		getActivity().getSupportFragmentManager().beginTransaction().show(frag).commit();
		
		return mParent;
	}
	
//	public void onEventMainThread(ClientUpdateNameNotFoundEvent event){
//		if(progressLoading!=null && progressLoading.isShowing()){
//			progressLoading.dismiss();
//		}
//		bgTask.getFBFeedList(LIMIT);
//	}
//	public void onEventMainThread(LatestVersionEvent event){
//		Log.e("latest","latest");
////		Toast.makeText(this, "Country: "+event.getCountryCode(), Toast.LENGTH_LONG).show();
////		PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.COUNTRY_CODE, event.getCountryCode()).commit();//event.getCountryCode()
//		if(progressLoading!=null && progressLoading.isShowing()){
//			progressLoading.dismiss();
//		}
//		bgTask.getFBFeedList(LIMIT);
//	}
//	public void onEventMainThread(AppStoreVnUpdateData data){
////		Toast.makeText(this, "Country: "+data.getCountryCode(), Toast.LENGTH_LONG).show();
//		if(progressLoading!=null && progressLoading.isShowing()){
//			progressLoading.dismiss();
//		}
//		updateUri = data.getUpdateUrl();
////		PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.COUNTRY_CODE, data.getCountryCode()).commit();//putString(Constants.COUNTRY_CODE, data.getCountryCode()).commit();//putString(Constants.COUNTRY_CODE, "vn").commit();
//		if(updateUri.startsWith("market")){
//			if(data.isForce()){
//				try {
//				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
//				    finish();
//				} catch (android.content.ActivityNotFoundException anfe) {
//				}
//			} else {
//				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putSerializable(HomeActivity.KEY_UPDATE_DATA, data);
//				showUpdate.putExtras(bundle);
//				startActivityForResult(showUpdate, REQUEST_CODE);
//			}
//		} else {
//			if(data.isForce()){
//					DownloadUpdateTask task = new DownloadUpdateTask(this);
//					task.setDownloadCallback(this);
//					task.execute(updateUri);
//			} else {
//				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putSerializable(HomeActivity.KEY_UPDATE_DATA, data);
//				showUpdate.putExtras(bundle);
//				startActivityForResult(showUpdate, REQUEST_CODE);
//			}
//		}
//		
//	}
	
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

		return cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}
//	private void checkTor(){
//		bgTask.checkTor();
//	}
	
//	public void onEventMainThread(GetTorStatusEvent event){
//		((AppStoreVnApplication)getApplication()).enableTor=event.status;
//		checkForUpdate();
//		if(pDialog!=null && pDialog.isShowing()){
//			pDialog.dismiss();
//		}
//	}
	
//	private void checkForUpdate(){
//		Log.e("checkForUpdate","cfu");
//		String deviceStatus;
//		apptoko.com.util.RootUtil root = new apptoko.com.util.RootUtil();
//		isRooted = root.isDeviceRooted();
//		((AppStoreVnApplication)getApplication()).setRooted(isRooted);
//		PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(Constants.IS_ROOTED, isRooted).commit();
//		if(isRooted){
//			deviceStatus = "1";
//		} else {
//			deviceStatus = "0";
//		}
//		progressLoading.show();
//		bgTask.checkClientUpdate(deviceStatus);
//	}
	
//	public void onEventMainThread(RequestUpdateFailEvent event){
//		if(event.getErrorCode() == -101){
//			AlertDialogManager am = new AlertDialogManager(this);
//			am.showPositiveDialog(R.string.couldnot_retrieve_data, R.string.retry, new DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					checkForUpdate();
//				}
//			});
//		}
//		else {
//			AlertDialogManager am = new AlertDialogManager(this);
//			am.showPositiveDialog(R.string.error, R.string.retry, new DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					checkForUpdate();
//				}
//			});
//		}
//	}
	
	@Override
	public void onResume() {
		super.onResume();
		EventBus.getDefault().unregister(this);
		EventBus.getDefault().register(this);
		EasyTracker.getTracker().sendView(currentStore + "/Newsfeed");
		com.facebook.AppEventsLogger.activateApp(getActivity(), getResources().getString(R.string.fb_app_id));
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
		
	}
	public void onEventMainThread(Event.FeedListSuccessEvent event){
		feedAllList=new ArrayList<FBFeedItem>();
//		feedList=new ArrayList<FBFeedItem>();
		START=0;
		List<FBFeedItem> list = event.getFeedList();
		Collections.sort(list, new CustomComparator());
		for(FBFeedItem feed : list){
			feedAllList.add(feed);
		}
		int index=0;
		if(START+5<feedAllList.size()){
			index=5;
		}else{
			index=feedAllList.size();
		}
		for(int i=0;i<index;i++){
			FBFeedItem feed =feedAllList.get(i);
			feedList.add(feed);
		}
		START=index;
//		listView.setAdapter(feedAdapter);
//		feedAdapter = new FeedItemAdapter(getActivity(), R.layout.feed_item, feedList);
		feedAdapter.notifyDataSetChanged();
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		listView.onLoadMoreComplete();
		listView.completeRefreshing();
//		if(feedList.size() <feedAllList.size()){
//			viewMore.setEnabled(true);
//			viewMore.setVisibility(View.VISIBLE);
//		}else{
//			viewMore.setEnabled(false);
//			viewMore.setVisibility(View.GONE);
//		}
	}
	
	public void onEventMainThread(Event.FeedListFailEvent event){
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		listView.completeRefreshing();
	}
	
	public void onEventMainThread(NetworkIOE event){
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		AppMsg.makeText(getActivity(), R.string.timeout, AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(AppJSONException event){
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		AppMsg.makeText(getActivity(), R.string.connect_error, AppMsg.STYLE_ALERT, null).show();
	}
	
	
	private class FeedItemAdapter extends ArrayAdapter<FBFeedItem> {
		
		private Typeface tf;
		private LayoutInflater li;
		private String httpURL;
		private ArrayList<String> pulledLink;
		private String title;
	//	private Bitmap preset;
		private OnInstallClickListener listener;
		private OnDownloadClickListener downloadClickListener;
		private OnDownloadClickListener viewYoutubeClickListener;
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = li.inflate(R.layout.feed_item, null);
				holder = new ViewHolder();
				holder.image = (ScaleImageView) convertView.findViewById(R.id.feed_image);
				holder.title = (TextView) convertView.findViewById(R.id.feed_title);
				holder.time = (TextView) convertView.findViewById(R.id.feed_time);
				holder.comments = (TextView) convertView.findViewById(R.id.comments_count);
				holder.btnInstall = (TextView) convertView.findViewById(R.id.btn_install);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final FBFeedItem item = getItem(position);
			if(item != null&&!item.getMessage().contains("youtube.com")){//
				aquery = new AQuery(convertView);
				if(aquery.getCachedFile(item.getPictureURL())!=null){
					aquery.id(holder.image).image(aquery.getCachedFile(item.getPictureURL()), 300);
					Log.e("NMN", "get feed images from CachedFiles");
				}else{
					Log.e("NMN","get feed images from server");
					aquery.id(holder.image).image(item.getPictureURL(), false, true, 0, R.drawable.ic_newsfeed_loading);
				}
				pulledLink = Utils.pullLinks(item.getMessage());
				if(pulledLink.size() > 0){
					httpURL = pulledLink.get(0);
				} else {
					httpURL = "";
				}
				title = item.getMessage().replace("[News] ", "").replace("[sNews] ", "").replace(httpURL, "");
				//title = title.substring(0, title.indexOf("\\n"));
				aquery.id(holder.title).text(title).typeface(tf).clickable(false);
				aquery.id(holder.time).text(item.getLikeCount() + " " + getString(R.string.likes)).typeface(tf);
				aquery.id(holder.comments).text(item.getCommentCount() + " " + getString(R.string.comments)).typeface(tf);
				if(TextUtils.isEmpty(httpURL)){
					aquery.id(holder.btnInstall).gone();
				} else if(httpURL.contains("?id=")){
					aquery.id(holder.btnInstall).visible();
					String packageName = httpURL.substring(httpURL.indexOf("?id=") + 4, httpURL.length());
					listener = new OnInstallClickListener(packageName);
					aquery.id(holder.btnInstall).text(R.string.menu_install).clicked(listener);
				} else {
					aquery.id(holder.btnInstall).visible();
					downloadClickListener = new OnDownloadClickListener(httpURL);
					aquery.id(holder.btnInstall).text(R.string.download).clicked(downloadClickListener);
				}
			}else if(item!=null){
				//item is video link
				aquery = new AQuery(convertView);
				pulledLink = Utils.pullLinks(item.getMessage());
				if(pulledLink.size() > 0){
					httpURL = pulledLink.get(0);
					feedAllList.get(feedAllList.indexOf(item)).youtubelink=httpURL;
				} else {
					httpURL = "";
				}
				String _imgYoutubeLink=pulledLink.get(0).substring(pulledLink.get(0).indexOf("watch?v=")+8, pulledLink.get(0).indexOf("&id="));
				String imgYoutubeLink="http://img.youtube.com/vi/"+_imgYoutubeLink+"/0.jpg";
				if(aquery.getCachedFile(imgYoutubeLink)!=null){
					aquery.id(holder.image).image(aquery.getCachedFile(imgYoutubeLink), 300);
					Log.e("NMN", "get feed images from CachedFiles");
				}else{
					Log.e("NMN","get feed images from server");
					aquery.id(holder.image).image(imgYoutubeLink, false, true, 0, R.drawable.ic_newsfeed_loading);
				}
				title = item.getMessage().replace("[News] ", "").replace("[sNews] ", "").replace(httpURL, "");
				//title = title.substring(0, title.indexOf("\\n"));
				aquery.id(holder.title).text(title).typeface(tf).clickable(false);
				aquery.id(holder.time).text(item.getLikeCount() + " " + getString(R.string.likes)).typeface(tf);
				aquery.id(holder.comments).text(item.getCommentCount() + " " + getString(R.string.comments)).typeface(tf);
				if(TextUtils.isEmpty(httpURL)){
					aquery.id(holder.btnInstall).gone();
				} else if(httpURL.contains("&id=")){
					aquery.id(holder.btnInstall).visible();
					String packageName = httpURL.substring(httpURL.indexOf("&id=") + 4, httpURL.length());
					listener = new OnInstallClickListener(packageName);
					aquery.id(holder.btnInstall).text(R.string.menu_install).clicked(listener);
				} else {
					aquery.id(holder.btnInstall).visible();
					downloadClickListener = new OnDownloadClickListener(httpURL);
					aquery.id(holder.btnInstall).text(R.string.download).clicked(downloadClickListener);
				}
			}
			return convertView;
		}

		public FeedItemAdapter(Context context, int resource, List<FBFeedItem> objects) {
			super(context, resource, objects);
			// TODO Auto-generated constructor stub
			li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			tf = Typeface.createFromAsset(context.getAssets(), getString(R.string.roboto_medium));
			pulledLink = new ArrayList<String>();
		}
		
	}
	
	public void onEventMainThread(ConvertLinkSuccess e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		String store = e.getStore();
		if(store.equalsIgnoreCase("ebook")){
			store = "books";
		} else if(store.equalsIgnoreCase("comic")){
			store = "comics";
		} else {
			store = "apps";
		}
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, e.getSlug(), Long.valueOf(1));
		if(e.getSlug().startsWith("market")||e.getSlug().startsWith("http")){
			try {
			    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(e.getSlug())));
			} catch (android.content.ActivityNotFoundException anfe) {
			}
		}else{
			Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
			intent.putExtra(Constants.PREVIOUS_SCREEN, "NewsFeed");
			intent.putExtra(Constants.SLUG, e.getSlug());
			intent.putExtra(Constants.KEY_REFERER, "direct");
			intent.putExtra(Constants.STORE_KEY, store);
			startActivity(intent);
		}
		
	}
	
	public void onEventMainThread(ConvertLinkFail e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
	}
	
	private class OnInstallClickListener implements OnClickListener {
		private String packageName;
		public OnInstallClickListener(String packageName){
			this.packageName = packageName;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			//String packageName = httpURL.substring(httpURL.indexOf("?id=") + 4, httpURL.length());
			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.NEWSFEED_DOWNLOAD, "Click Install from Newsfeed"+packageName, Long.valueOf(1));
			Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
			intent.putExtra(Constants.PREVIOUS_SCREEN, "NewsFeed");
			intent.putExtra(Constants.PACKAGE_NAME, packageName);
			intent.putExtra(Constants.KEY_REFERER, "direct");
			intent.putExtra(Constants.STORE_KEY, "apps");
			startActivity(intent);
		}
	}
	
	private class OnDownloadClickListener implements OnClickListener {
		private String link;
		public OnDownloadClickListener(String link){
			this.link = link;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.NEWSFEED_DOWNLOAD, link, Long.valueOf(1));
			pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
			accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.convertLink(accessToken, link);
		}
	}
	
//	private class OnClickYoutubeLinkListener implements OnClickListener {
//		private String link;
//		public OnClickYoutubeLinkListener(String link){
//			this.link = link;
//		}
//		@Override
//		public void onClick(View v) {
//			// TODO Auto-generated method stub
//			EasyTracker.getTracker().sendEvent(Constants.YOUTUBE_VIEW_EVENT_CATEGORY, Constants.VIEW_EVENT_ACTION, link, Long.valueOf(1));
//			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
//			startActivity(browserIntent);
//		}
//	}
	
	private static class ViewHolder{
		ScaleImageView image;
		TextView title;
		TextView time;
		TextView comments;
		TextView btnInstall;
	}
	private boolean isready=false;
	private void viewMore(){
		int limit=0;
		if(START+5<feedAllList.size()){
			limit=5;
		}else{
			limit=(feedAllList.size()-START);
		}
		for(int i=START;i<limit+START;i++){
			FBFeedItem feed =feedAllList.get(i);
			feedList.add(feed);
		}
		feedAdapter.notifyDataSetChanged();
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		listView.onLoadMoreComplete();
		listView.completeRefreshing();
		listView.smoothScrollToPosition(START+1);
		if(START+5<feedAllList.size()){
			START+=5;
		}else{
			START+=(feedAllList.size()-START);
		}
		if(feedList.size() <feedAllList.size()){
		}else{
			listView.setOnLoadMoreListener(null);
		}
	}
	Runnable runnable=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			doLoadMore();
		}
	};
	
	private void doLoadMore(){
		progressBar.setVisibility(View.INVISIBLE);
		int limit=0;
		if(START+5<feedAllList.size()){
			limit=5;
		}else{
			limit=(feedAllList.size()-START);
		}
		for(int i=START;i<limit+START;i++){
			FBFeedItem feed =feedAllList.get(i);
			feedList.add(feed);
		}
		feedAdapter.notifyDataSetChanged();
		aquery.id(R.id.progress).gone();
		aquery.id(listView).visible();
		listView.onLoadMoreComplete();
		listView.completeRefreshing();
		listView.smoothScrollToPosition(START+1);
		if(START+5<feedAllList.size()){
			START+=5;
		}else{
			START+=(feedAllList.size()-START);
		}
		if(feedList.size() <feedAllList.size()){
		}else{
			listView.setOnLoadMoreListener(null);
		}
	}
	
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
//		feedAdapter.clear();
//		LIMIT = LIMIT + 20;
//		bgTask.getFBFeedList(LIMIT);
		progressBar.setVisibility(View.VISIBLE);
		handler.postDelayed(runnable,3000);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		FBFeedItem item = (FBFeedItem) parent.getItemAtPosition(pos+1);
		if(item.isYouTubeLink){
			EasyTracker.getTracker().sendEvent(Constants.YOUTUBE_VIEW_EVENT_CATEGORY, Constants.VIEW_EVENT_ACTION, item.youtubelink, Long.valueOf(1));
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.youtubelink));
			startActivity(browserIntent);
			return;
		}
		EasyTracker.getTracker().sendEvent("View Feed Detail", "Open Newsfeed Detail","Open Newsfeed Detail" , Long.valueOf(1));
		Bundle b = new Bundle();
		b.putString(Constants.NEWSFEED_ID, item.getId());
		b.putString(Constants.NEWSFEED_TITLE, item.getMessage());
		b.putString(Constants.NEWSFEED_IMAGE, item.getPictureURL());
		b.putBoolean(Constants.NEWSFEED_CAN_LIKE, item.isCanLike());
		b.putBoolean(Constants.NEWSFEED_USER_LIKES, item.isUserLike());
		Intent intent = new Intent(getActivity(), FeedDetailsActivity.class);
		intent.putExtras(b);
		startActivity(intent);
	}

	@Override
	public void onRefresh(PullToRefreshListView listView) {
		// TODO Auto-generated method stub
		feedAdapter.clear();
		bgTask.getFBFeedList(LIMIT);
		this.listView.setOnLoadMoreListener(this);
	}
	
	private class CustomComparator implements Comparator<FBFeedItem> {
		@Override
		public int compare(FBFeedItem obj1, FBFeedItem obj2) {
			// TODO Auto-generated method stub
			return obj1.getOrder() < obj2.getOrder() ? -1
			         : obj1.getOrder() > obj2.getOrder() ? 1
			         : 0;
		}
	}
	
	private String topType;
	@Override
	protected void initVariables() {
		EasyTracker.getInstance().setContext(mContext);
		accessToken = Utils.getStaticAccessToken(getActivity());
		topType = getArguments().getString(Constants.TOP);
		currentStore = getArguments().getString(Constants.STORE_KEY);
		aquery = new AQuery(getActivity());
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		if(bgTask==null){
			bgTask = new BackgroundTasks(getActivity());
		}
		bgTask.getFBFeedList(LIMIT);
	}
	
//	public class GetLAAsync extends AsyncTask<Void, Void, Void>{
//
//		@Override
//		protected Void doInBackground(Void... params) {
//
//			return null;
//		}
//		@Override
//		protected void onPostExecute(Void result) {
//			// TODO Auto-generated method stub
//			myLocation.getLocation(NewsFeedActivity.this, locationResult);
//		}
//		
//	}
//	LocationResult locationResult;
//	public void getLA(){
//		locationResult = new LocationResult(){
//		    @Override
//		    
//
//		        public void gotLocation(Location location){
////		    	Toast.makeText(NewsFeedActivity.this, location.get, duration);
//				try {
//					Geocoder geocoder = new Geocoder(NewsFeedActivity.this,
//							Locale.ENGLISH);
//					List<Address> addresses = geocoder.getFromLocation(
//							location.getLatitude(), location.getLongitude(), 2);
//					String add = "";
//					if (addresses != null) {
//						add = addresses.get(0).getCountryCode();
////						Toast.makeText(NewsFeedActivity.this, add,
////								Toast.LENGTH_LONG).show();
////						for (int j = 0; j < 2; j++) {
////							Address returnedAddress = addresses.get(j);
////							StringBuilder strReturnedAddress = new StringBuilder();
////							for (int i = 0; i < returnedAddress
////									.getMaxAddressLineIndex(); i++) {
////								strReturnedAddress.append(
////										returnedAddress.getCountryCode());
////							}
////							add += strReturnedAddress.toString() + " | ";
////						}
//					}else{
//						AlertDialog.Builder builder=new Builder(NewsFeedActivity.this);
//						builder.setMessage("Unexpected problem, exit app..").setPositiveButton("Exit", new DialogInterface.OnClickListener() {
//							
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								dialog.dismiss();
//								finish();
//							}
//						});
//					}
//					PreferenceManager.getDefaultSharedPreferences(NewsFeedActivity.this).edit().putString(Constants.COUNTRY_CODE, add).commit();
//					checkTor();
//					Log.e("LA","LA:"+add);
//				} catch (Exception ex) {
//					ex.printStackTrace();
//				}
//		    }
//		};
//		new GetLAAsync().execute();
//	}
//	HttpLa myLocation = new HttpLa();
}
